package top.heue.utils.log.printer

import top.heue.utils.log.LogLevel
import top.heue.utils.log.base.BasePrinter
import java.io.File
import java.time.LocalDate
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter

class FilePrinter(
    private val logsDir: File,
    private val filePrefix: String,
    private val fileExt: String,
) : BasePrinter() {
    private val lock = Any()
    private val dateFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
    private val tsFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSXXX")
    private val nowString: String get() = ZonedDateTime.now().format(tsFormatter)
    override fun println(logLevel: LogLevel, tag: String, string: String) {
        try {
            val line = "[$nowString][${logLevel.name[0]}][$tag] $string"
            synchronized(lock) {
                if (!logsDir.exists()) logsDir.mkdirs()
                val file = currentLogFile()
                file.appendText(line + System.lineSeparator(), Charsets.UTF_8)
            }
        } catch (_: Throwable) {
        }
    }

    private fun currentLogFile(): File {
        val date = LocalDate.now().format(dateFormatter)
        return File(logsDir, "$filePrefix $date$fileExt")
    }

    fun cleanupOldLogs(retentionDays: Long) {
        val cutoff = LocalDate.now().minusDays(retentionDays)
        val files = logsDir.listFiles { _, name ->
            name.startsWith(filePrefix) && name.endsWith(fileExt)
        } ?: return
        for (f in files) {
            val datePart = f.name.removePrefix(filePrefix).removeSuffix(fileExt)
            val fileDate = runCatching { LocalDate.parse(datePart, dateFormatter) }.getOrNull()
            if (fileDate == null) continue
            if (fileDate.isBefore(cutoff)) {
                runCatching { f.delete() }
            }
        }
    }
}
